<?php

class db extends BaseAction {

	public function migrate(){
		if(!isset($GLOBALS['argv'][2]) || !file_exists("views/".$GLOBALS['argv'][2].".php")) _exit(2);
		$name = $GLOBALS['argv'][2];
		
		$chktbl = sqlite_query("SELECT tbl_name FROM sqlite_master WHERE type='table'",$GLOBALS['expdb']);
		while($db = sqlite_fetch_array($chktbl)){
			if($db['tbl_name']==$name){
				echo verbose_message("== Skipping view: $name (already exists)");
				return false;
			}
		}
		echo verbose_message("== Migrating view: $name");
		$query  = "create table $name (";
		$query .= "time INTEGER PRIMARY KEY,";
		
		require_once("views/$name.php");

		$vw = new $name();
		$schema = $vw->exec();
		
		switch($schema[0]){
			case "map":
				$data = $schema[2];
				$cols = array();
				foreach($schema[1] as $col=>$type){
					$cols[] = $col;
					$query .= "$col $type,";
				}
				$query[strlen($query)-1] = ')';
				$query .= '; ';

				reset($data);				
				$header = current($data);
				foreach($cols as $k=>$col){
					$cols[$col] = array_search($col,$header);
					unset($cols[$k]);
				}
				
				while($row = next($data)){
					$query .= "insert into $name (";
					foreach($cols as $col=>$pos){
						$query .= "$col,";
					}
					$query[strlen($query)-1] = ')';
					$query .= ' values (';
					foreach($cols as $col=>$pos){
						$query .= "{$row[$pos]},";
					}
					$query[strlen($query)-1] = ')';
					$query .= '; ';
				}
				break;
			case "pattern":
				$query .= ");";
				break;
			case "join":
				$query .= ");";
				break;
		}
		$queries = explode(';',$query);
		$n = count($queries);
		echo verbose_message("== Writing to database... ($n total transactions)");
	//	log_message($query);
	  echo "     ";
		foreach($queries as $query){
			$exec = sqlite_exec($query, $GLOBALS['expdb']);
			$i++;
			if($i%500==0) echo ".";
		}
		echo "\n";
		if(!$exec){
			echo verbose_message("== Migration failed: ".sqlite_error_string(sqlite_last_error($GLOBALS['expdb'])));
			return false;
		} else {
			echo verbose_message("== Migration successful");
			return true;
		}
	}
	
	public function query(){
		if(!isset($GLOBALS['argv'][2])) _exit(2);
		$query = $GLOBALS['argv'][2];
		
		$query = sqlite_query($query,$GLOBALS['expdb']);
		$query = sqlite_fetch_all($query,SQLITE_ASSOC);
		
		print_r($query);
	}
	
	public function import(){
		// TODO: Import $name mapped from /data/canonical into the database as a canonical
		// dataset.
		return false;
	}

}